package com.spleeb.pixelengine;

import java.util.ArrayList;

import android.graphics.Canvas;
import android.view.SurfaceHolder;

public class GameLoop implements Runnable {
	public static final int frames_per_second = 60;
	public static final int maxfpms = 1000/frames_per_second;
	public SurfaceHolder surfaceHolder;
	public boolean running = true;
	public GameView view;
	public ArrayList<ProcessHandler> processes = new ArrayList<ProcessHandler>();
	public GameLoop(GameView view,SurfaceHolder surfaceHolder){
		this.surfaceHolder = surfaceHolder;
		this.view = view;
		Thread thread = new Thread(this);
		thread.start();
	}
	public void run() {
		Canvas canvas;
		long started;
		while(running){
			view.EnterFrame();
			canvas = null;
			try{
				canvas = surfaceHolder.lockCanvas();
			synchronized(surfaceHolder){
				started = System.currentTimeMillis();
				if (canvas!=null){
				view.Draw(canvas);
				}
				long now = System.currentTimeMillis();
				if (now-started<maxfpms){
					try{Thread.sleep(maxfpms - (now-started));}
					catch(InterruptedException e){
					}
				}
			}
			}finally{
				if (canvas!=null){
					surfaceHolder.unlockCanvasAndPost(canvas);
				}
			}
		}
	}
	
}
